from PyQt4.QtGui import QTreeView, QAbstractItemView, QWidget, QSlider, QSpinBox, QHBoxLayout, QVBoxLayout, QListView, \
                        QListWidget, QListWidgetItem, QLabel, QWidget, QAction, QToolButton, QStandardItemModel, QStandardItem, \
                        QHeaderView, QMenu, QPixmap, QFileDialog, QLineEdit, QPushButton, QSizePolicy, QComboBox, \
                        QVBoxLayout
from PyQt4.QtCore import SIGNAL, Qt, QSize

from notify.signal import Signal

from ui.delegates import QListEditorDelegate, AttrEditorDelegate, AttrDelegate
from ui.models import QListModel, QListEditorModel, SelectionModel, DataModel

from core.std import Component

from core import cmds, util
from core.base import ComponentSelected
#from core.graph import Pipeline

import os, sys



class PipelineComboBox(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.combobox = QComboBox(self)
        self.new_pipeline_btn = QToolButton(self)
        self.new_pipeline_act = QAction(self)
        self.new_pipeline_act.setText("+")
        self.connect(self.new_pipeline_act, SIGNAL("triggered()"), self.new_pipeline)
        self.new_pipeline_btn.setDefaultAction(self.new_pipeline_act)
        
        layout = QHBoxLayout()
        layout.addWidget(self.combobox)
        layout.addWidget(self.new_pipeline_btn)
        layout.setMargin(0)
        layout.setSpacing(0)
        self.setLayout(layout)
        
        self.pipelines = []
        self.combobox.setEditable(True)
        
        self.connect(self.combobox, SIGNAL("editTextChanged(const QString&)"), self.text_edited)
        self.connect(self.combobox, SIGNAL("currentIndexChanged(int)"), self.index_selected)
        self.refresh()
        
    def new_pipeline(self):
        pipe = cmds.new_component("Pipeline")
        self.pipelines.append(pipe)
        self.add_pipeline(pipe)
        self.combobox.setFocus()
        self.combobox.setCurrentIndex(self.combobox.count()-1)
        self.combobox.lineEdit().selectAll()
    
    def add_pipeline(self, pipe):
        self.combobox.addItem(str(pipe.name))
    
    def current_pipeline(self):
        return self.pipelines[self.combobox.currentIndex()]
    
    def text_edited(self, text):
        self.current_pipeline().name = str(text)
        
    def refresh(self):
        self.combobox.clear()
        self.pipelines = cmds.ls("Pipeline")
        for pipeline in self.pipelines:
            self.add_pipeline(pipeline)
            
    def index_selected(self, index):
        cmds.select(self.pipelines[index])

class QCellWidget(QTreeView):
    def __init__(self, parent=None):
        QTreeView.__init__(self, parent)
        self.setModel(QListModel())
        self.setItemDelegate(AttrDelegate())
        self.setSelectionModel(SelectionModel(self.model()))
        self.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.setAlternatingRowColors(True)
        self.setDragDropMode(QAbstractItemView.DragOnly)
        self.setDragEnabled(True)
        
    def on_item_pressed(self,index):
        item = self.model().itemFromIndex(index)
        data = item.data_obj
        if isinstance(data, Component):
            ComponentSelected(data)
        
    def resizeColumnsToContents(self):
        self.header().resizeSections(QHeaderView.ResizeToContents)
        
    def open_all_editors(self):
        for item in self.model().items():
            index = self.model().indexFromItem(item)
            self.openPersistentEditor(index)
     
    def reset(self):
        self.model().update() 
      
    def set_content(self, content):
        self.model()._data = content
    def get_content(self):
        return self.model()._data
    content = property(get_content, set_content)

        
        


class PathFinder(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.main_layout = QHBoxLayout()
        self.main_layout.setSpacing(0)
        self.main_layout.setMargin(0)
        
        self.path_edit = QLineEdit(self)
        self.path_dialog_btn = QPushButton(self)
        
        self.path_dialog_btn.setText("Choose")
        
        self.main_layout.addWidget(self.path_edit)
        self.main_layout.addWidget(self.path_dialog_btn)
        
        self.setLayout(self.main_layout)
        
        self.connect(self.path_edit, SIGNAL("editingFinished()"), lambda: self.emit(SIGNAL("pathChanged")))
        self.connect(self.path_dialog_btn, SIGNAL("pressed()"), self.button_clicked)
        
    def setPath(self, path):
        self.path_edit.setText(str(path))
        
    def path(self):
        return str(self.path_edit.text())
        
    def button_clicked(self, *args, **kw):
        path = QFileDialog.getExistingDirectory(self, "Open Directory",
                                                 "",
                                                 QFileDialog.ShowDirsOnly
                                                 | QFileDialog.DontResolveSymlinks)
        if not path: return
        self.path_edit.setText(str(path))
        self.emit(SIGNAL("pathChanged"))
        
    
        

class QMenuWidget(QMenu):
    def __init__(self, parent=None):
        QMenu.__init__(self, parent)
        self._model = QListModel()
        self.checkable = False
        self.checked = None
    
    def create_menu(self):
        self._model.update()
        self.clear()
        for item in self._model.items():
            act = QAction(self)
            act.setText(str(item.text()))
            act.setCheckable(self.checkable)
            if self.checked:
                act.setChecked(self.checked(item.data_obj))
            act.connect(act, SIGNAL("toggled(bool)"), lambda b, i=item: self.action_toggled(b, i))
            self.addAction(act)
        
    def action_toggled(self, checked, item):
        self.emit(SIGNAL("itemToggled"), item.data_obj, checked)
        

class ImageWidget(QLabel):
    def __init__(self, parent=None):
        QLabel.__init__(self, parent)
        self.setScaledContents(True)
        
    def load(self, path):
        pixmap = QPixmap()
        pixmap.load(path)
        self.setPixmap(pixmap)
        self.adjustSize()
        
        
class QListEditor(QListView):
    def __init__(self, parent=None):
        QListView.__init__(self, parent)
        self.setModel(QListEditorModel())
        self.setItemDelegate(QListEditorDelegate())

    def set_items(self, items):
        self.model().set_items(items)
        self.setFixedHeight(19*(len(items)+1))
    
'''       
class QListEditor(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self._main_layout = QVBoxLayout()
        #self.widgets =
'''
            
class QContainerViewWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.main_layout = QHBoxLayout()
        self.widget = None
        self.setLayout(self.main_layout)
        
    def add_widget(self, widget):
        if self.widget:
            self.widget.setParent(None)
            self.widget.hide()
            self.widget.deleteLater()
        self.main_layout.addWidget(widget)
        self.widget = widget
 
class QSliderField(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        
        self.slider = QSlider(self)
        self.field  = QSpinBox(self)
        
        self.slider.setOrientation(Qt.Horizontal)
        
        self.main_layout = QHBoxLayout()
        self.main_layout.addWidget(self.slider)
        self.main_layout.addWidget(self.field)
        
        self.setLayout(self.main_layout)
        
        self.connect(self.slider, SIGNAL("valueChanged(int)"), self.on_value_change)
        self.connect(self.field, SIGNAL("valueChanged(int)"), self.on_value_change)
        self.connect(self.slider, SIGNAL("sliderReleased()"), self.editing_finished)
        self.connect(self.field, SIGNAL("editingFinished()"), self.editing_finished)
        

    def editing_finished(self):
        self.emit(SIGNAL("editingFinished"))
        
    def setMinimum(self, value):
        if value is None:
            self.slider.hide()
            return
        self.slider.setMinimum(value)
        self.field.setMinimum(value)
        
    def setMaximum(self, value):
        if value is None:
            self.slider.hide()
            return
        self.slider.setMaximum(value)
        self.field.setMaximum(value)
        
    def on_value_change(self, value):
        self.setValue(value)
        self.emit(SIGNAL("valueChanged"), int(value))
        
    def value(self):
        return int(self.slider.value())
        
    def setValue(self, value):
        if value is None: return
        self.slider.setValue(value)
        self.field.setValue(value)
        
